package edu.tjpu.share.newui;

import java.util.HashMap;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import edu.tjpu.share.R;
import edu.tjpu.share.app.Fields;
import edu.tjpu.share.po.Server;
import edu.tjpu.share.po.UserVo;
import edu.tjpu.share.task.RegisterTask;
import edu.tjpu.share.task.UserModifyTask;

public class UserRegister extends Activity {

	private Server serverinfo;
	private int mid;
	private int gid;
	private int cid;
	private EditText uname;
	private EditText upasswd;
	private EditText repasswd;
	private TextView create_account_label_username,
			create_account_label_password,
			create_account_label_confirm_password;
	private Button register;
	static UserVo userBack;
	private boolean isModify;
	private UserVo user;
	private SharedPreferences share;

	ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create_account);

		uname = (EditText) findViewById(R.id.create_account_username);
		upasswd = (EditText) findViewById(R.id.create_account_password);
		repasswd = (EditText) findViewById(R.id.create_account_confirm_password);
		register = (Button) findViewById(R.id.create_account_button);
		create_account_label_username = (TextView) findViewById(R.id.create_account_label_username);
		create_account_label_password = (TextView) findViewById(R.id.create_account_label_password);
		create_account_label_confirm_password = (TextView) findViewById(R.id.create_account_label_confirm_password);
		share = this.getSharedPreferences("perference", MODE_PRIVATE);
		Intent intent = this.getIntent();
		Bundle bundle = intent.getExtras();

		serverinfo = (Server) bundle.getSerializable(Fields.SERVER_INFO);
		isModify = bundle.getBoolean("isModify", false);
		if (isModify) {
			create_account_label_username.setText("原密码");
			create_account_label_password.setText("新密码");
			create_account_label_confirm_password.setText("重复新密码");
			register.setText("确定修改");
			setTitle("修改密码");
			uname.setHint("旧密码");
			uname.setInputType(InputType.TYPE_CLASS_TEXT
					| InputType.TYPE_TEXT_VARIATION_PASSWORD);
			user = (UserVo) bundle.getSerializable(Fields.USER);
		} else {
			gid = (Integer) bundle.getSerializable(Fields.GID);
			mid = (Integer) bundle.getSerializable(Fields.MID);
			cid = (Integer) bundle.getSerializable(Fields.CID);
		}

		userBack = null;

		register.setOnClickListener(new View.OnClickListener() {

			@SuppressWarnings("unchecked")
			@Override
			public void onClick(View v) {
				String unamestr = uname.getText().toString().trim();
				String upasswdstr = upasswd.getText().toString().trim();
				String repasswdstr = repasswd.getText().toString().trim();

				if (unamestr != null && !"".equals(unamestr)
						&& upasswdstr != null && !"".equals(upasswdstr)
						&& repasswdstr != null && !"".equals(repasswdstr)
						&& repasswdstr.equals(upasswdstr)) {
					if (upasswdstr.length() < 6) {
						Toast.makeText(UserRegister.this, "密码不能小于6位，请重新输入！",
								Toast.LENGTH_SHORT).show();
					} else {

						if (isModify) {
							user.setXmppUsername(upasswdstr);
							user.setUpasswd(unamestr);
							HashMap<String, Object> map = new HashMap<String, Object>();
							map.put(Fields.SERVER_INFO, serverinfo);
							map.put(Fields.USER, user);
							map.put(Fields.HANDLER, handler);
							map.put(Fields.IMAGE_UNSPECIFIED, false);

							new UserModifyTask().execute(map);
							progressDialog = ProgressDialog.show(
									UserRegister.this, "请稍等...", "正在连接服务器...",
									true);
						} else {
							UserVo user = new UserVo();
							user.setUname(unamestr);
							user.setUpasswd(upasswdstr);
							user.setCid(cid);
							user.setGid(gid);
							user.setMid(mid);

							HashMap<String, Object> map = new HashMap<String, Object>();
							map.put(Fields.SERVER_INFO, serverinfo);
							map.put(Fields.USER, user);
							map.put(Fields.HANDLER, handler);

							new RegisterTask().execute(map);
							progressDialog = ProgressDialog.show(
									UserRegister.this, "请稍等...", "正在连接服务器...",
									true);
						}
					}
				} else {
					Toast.makeText(UserRegister.this, "输入信息有误，请重新输入！",
							Toast.LENGTH_SHORT).show();

				}
			}
		});

	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == Fields.NETWORK_CONNECTION_ERROR) {
				progressDialog.dismiss();
				Toast.makeText(UserRegister.this, "网络错误！", Toast.LENGTH_SHORT)
						.show();
			} else {
				if (!isModify) {
					if (userBack != null&&userBack.getUid() != 0) {

						Intent intent = new Intent();
						Bundle bundle = new Bundle();
						bundle.putSerializable(Fields.USER, userBack);
						bundle.putSerializable(Fields.SERVER_INFO, serverinfo);
						intent.putExtras(bundle);

						progressDialog.dismiss();
						Toast.makeText(UserRegister.this, "注册成功！",
								Toast.LENGTH_SHORT).show();
						Editor editor = share.edit();
						editor.putString(Fields.USER_NAME, uname.getText().toString().trim());
						editor.putString(Fields.USER_PASSWD, upasswd.getText().toString().trim());
						// editor.putBoolean("isLogedIn", true);
						editor.commit();
						intent.setClass(UserRegister.this, Login.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // 清除该进程空间的所有Activity
						startActivity(intent);
						finish();
					} else if (userBack.getUid() == 0) {
						progressDialog.dismiss();
						Toast.makeText(UserRegister.this, "用户名已经存在！",
								Toast.LENGTH_SHORT).show();
					} else {

						progressDialog.dismiss();
						Toast.makeText(UserRegister.this, "注册失败！",
								Toast.LENGTH_SHORT).show();
					}
				} else {
					if (msg.what == Fields.SUCCESS) {
						progressDialog.dismiss();
						Toast.makeText(UserRegister.this, "修改成功！",
								Toast.LENGTH_SHORT).show();
						SharedPreferences share = getSharedPreferences(
								"perference", MODE_PRIVATE);
						Editor editor = share.edit();// 取得编辑器
						editor.putString(Fields.USER_PASSWD, "");
						editor.commit();// 提交刷新数据
						Toast.makeText(UserRegister.this, "储存的旧密码已删除！",
								Toast.LENGTH_SHORT).show();
						Intent intent = new Intent();
						intent.setClass(UserRegister.this, MainTabHost.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // 清除该进程空间的所有Activity
						startActivity(intent);
						finish();
					} else {
						progressDialog.dismiss();
						Toast.makeText(UserRegister.this, "修改失败！",
								Toast.LENGTH_SHORT).show();
					}
				}
			}
		}
	};

	public static void setUserBack(UserVo userBack) {
		UserRegister.userBack = userBack;
	}

	/*
	 * @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
	 * 
	 * // 按下键盘上返回按钮 if (keyCode == KeyEvent.KEYCODE_BACK) {
	 * 
	 * new AlertDialog.Builder(this) .setTitle("警告") .setMessage("您确定要退出吗？")
	 * .setNegativeButton("取消", new DialogInterface.OnClickListener() {
	 * 
	 * @Override public void onClick(DialogInterface dialog, int which) { } })
	 * .setPositiveButton("确定", new DialogInterface.OnClickListener() { public
	 * void onClick(DialogInterface dialog, int whichButton) { finish(); }
	 * }).show();
	 * 
	 * return true; } else { return super.onKeyDown(keyCode, event); } }
	 */
}
